/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package mundialfp.view.tables.paisABM;

import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;
import mundialfp.view.tables.PaisTableModel;
import mundialfp.view.tables.TableUtils;

/**
 *
 * @author pferraz
 */
public class PaisTableSorter {
  
    
    public void initQuickSearch(final JTable table,final JTextField textBox,final int banderaHeight,int columnToSort) {

        final TableRowSorter<PaisTableModel> sorter = new TableRowSorter<>((PaisTableModel) table.getModel());
        final int sorterColumn=columnToSort;
        table.setRowSorter(sorter);
        TableUtils.setHeight(table, banderaHeight);
        textBox.getDocument().addDocumentListener(
                new DocumentListener() {
                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        newFilter();
                    }

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        newFilter();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        newFilter();
                    }

                    /**
                     * Update the row filter regular expression from the
                     * expression in the text box.
                     */
                    private void newFilter() {
                        if (!textBox.getText().equalsIgnoreCase("Búsqueda rápida ...")) {
                            RowFilter<PaisTableModel, Object> rf;
                        //If current expression doesn't parse, don't update.
                            //(?i) hace que la expresion regular sea case insensitive
                            try {
                                rf = RowFilter.regexFilter("(?i)" + textBox.getText(), sorterColumn);
                            } catch (java.util.regex.PatternSyntaxException e) {
                                return;
                            }
                            sorter.setRowFilter(rf);
                            TableUtils.setHeight(table, banderaHeight);
                        }
                    }
                });
    }
}
